<template>
  <div>
    <a-input 
      placeholder="选择样本编号"
      v-model="sampleDesc"
      @click="showModal"
      allowClear
      >
      <a-icon slot="addonAfter" type="ordered-list" @click="showModal" />
    </a-input>

    <a-modal 
      title="选择样本编号"
      centered
      :maskClosable="false"
      :width="1000"
      v-model="visible"
      :okText="$t('modal_ok')"
      :cancelText="$t('modal_cancel')"
      @ok="handleOk"
    >
      <a-form layout="inline" class="default-search-form" :form="form" @submit="handleSearch">
        <a-row>
          <a-col span="8">
            <a-form-item label="">
              <a-input v-decorator="['sampleCode']" placeholder="样本编号"/>
            </a-form-item>
          </a-col>
          <a-col span="8">
            <a-form-item label="">
              <a-input v-decorator="['sampleName']" placeholder="受检者姓名"/>
            </a-form-item>
          </a-col>
          <a-col span="8">
            <a-form-item class="gb-search-button">
              <a-button class="item" type="primary" html-type="submit">
                {{ $t('search') }}
              </a-button>
              <a-button type="primary" class="item" @click="handleReset">
                {{ $t('reset') }}
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-table :columns="columns"
        :rowKey="record => record.id"
        :dataSource="data"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio'}"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        size="small"
       :scroll="{ x: 800 }"
      >

      </a-table>
    </a-modal>
  </div>
</template>
<script>
import axios from 'axios'
import common from '@/global/common.js'
export default {
  mounted: function(){
    this.fetch()
  },
  watch:{
    value: function() {
      this.resolveLabel()
      this.selectedRowKeys =  [this.value]
    },
    departmentId() {
      this.$emit('change', '')
      this.fetch()
    },
    sampleDesc: function(val) {
      if (val == undefined || val.length == 0) {
        // 通过allowClear图标清空值触发
        this.$emit('change', '')
      }
    },
    data() {
      if (!this.sampleDesc) {
        this.resolveLabel()
      }
    }
  },
  props: {
    value: { type: [String], },
    departmentId: { type: [String] },
    isDepartmentRequired: { type: [Boolean] , deafult: false },
  },
  data() {
    return {
      visible: false,
      sampleDesc: '',
      form: this.$form.createForm(this, {name: this._uid}),
      data: [],
      loading: true,
      selectedRowKeys: [this.value],
      selectedRows: [],
      pagination: { sortField: 'sample_code', sortOrder: 'ascend', ...common.getPagination(), size: 'small'},
    }
  },
  computed: {
    columns() {
      const columns = [
        { title: '样本编号', dataIndex: 'sampleCode', sorter: true, defaultSortOrder:'ascend', key: 'sample_code', customRender: (text) => { return <LongTableColumn>{text}</LongTableColumn> }, width: 300, },
        { title: '受检者姓名', dataIndex: 'sampleName', sorter: true, key: 'sample_name', customRender: (text) => { return <LongTableColumn>{text}</LongTableColumn> }, width: 500, },
      ]
      return columns
    }
  },
  methods: {
    showModal() {
      this.visible = true
      this.selectedRowKeys =  [this.value]
      this.fetch()
    },
    handleSearch (e) {
      if(e){
        this.pagination.current = 1
        e.preventDefault()
      }
      this.fetch()
    },
    handleReset () {
      this.form.resetFields()
      this.handleSearch()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination.pageSize = pagination.pageSize
      this.pagination.current = pagination.current
      this.pagination.sortField = ''
      this.pagination.sortOrder = ''
      if (sorter.column) {
        this.pagination.sortField = sorter.columnKey
        this.pagination.sortOrder = sorter.order
      }
      this.fetch({
        ...filters,
      })
    },
    resolveLabel() {
      let val = this.value || ''
      if (val == undefined || val.length == 0) {
        this.sampleDesc = ''
        return
      }

      let data = this.data || []
      let selectedRecord = data.find(item => item.id == this.value)

      if (selectedRecord) {
        this.sampleDesc = selectedRecord.sampleCode
      }
    },
    fetch (param = {}) {
      if (this.isDepartmentRequired && !this.departmentId) {
        this.pagination.total = 0
        this.data = []
      }

      this.form.validateFields((err, formValue) => {
        if (err) {
          return
        }
        this.loading = true
        axios({
          url: '/backend/sample/findPendingSample',
          method: 'get',
          params: {
            pageSize: this.pagination.pageSize,
            pageNum: this.pagination.current,
            sortField: this.pagination.sortField,
            sortOrder: this.pagination.sortOrder,
            ...param,
            ...formValue,
            id: this.value,
          },
        }).then((res) => {
          this.pagination.total = res.data.total
          this.loading = false
          this.data = res.data.rows
        })
      })
    },
    handleOk() {
      let row = this.selectedRows[0]
      this.visible = false
      this.$emit('change', row.id)
      this.$emit('changeAll', row);
      this.sampleDesc = row.sampleCode
    },
  }
}
</script>
